import { useLocation, useNavigate } from "umi";
import Editor from "@monaco-editor/react";
import { Button, InputNumber, message } from "antd";
import React, { useState, useEffect, useRef } from "react";
import { postRealog } from "@/services/hosting/api";

const Realog: React.FC = () => {
    const location = useLocation();
    const params = new URLSearchParams(location.search);
    const appId = params.get("appId") || "";
    const [code, setCode] = useState<string>("// 点击连接后，即可查看应用日志\n");
    const editorRef = useRef<any>(null);
    const [fontSize, setFontSize] = useState<number>(14);
    const [isAutoScrolling, setIsAutoScrolling] = useState(true);
    const scrollTimeoutRef = useRef<NodeJS.Timeout | null>(null);
    const offsetRef = useRef<number>(0);
    const pollingIntervalRef = useRef<number | null>(null);
    const [isPolling, setIsPolling] = useState(false);
    const navigate = useNavigate();
    const stype = params.get("type") || "";
    const nodeId = params.get("nodeId") || "";
    
    // 滚动到底部
    const scrollToBottom = () => {
        if (editorRef.current) {
            editorRef.current.revealLine(editorRef.current.getModel().getLineCount());
        }
    };
    
    const getLog = async (body: any) => {
        try {
            const res: any = await postRealog(body, stype, nodeId, navigate);
            // 根据后端实现，检查响应数据结构
            if (res?.message?.logs?.length) {
                // 如果是首次加载历史日志，替换默认文本
                if (offsetRef.current === 0) {
                    setCode(res.message.logs.join("\n") + "\n");
                } else {
                    setCode(prev => prev + res.message.logs.join("\n") + "\n");
                }
                if (res.message.next_offset !== undefined) {
                    offsetRef.current = res.message.next_offset;
                }
            } else if (res?.message?.code === 401) {
                message.info("应用未运行或日志不可用");
                stopPolling();
            }
        } catch (error: any) {
            console.error("日志拉取失败:", error);
            message.error(error?.message || "日志拉取失败");
        }
    };

    const startPolling = () => {
        if (isPolling) return;
        // 重置offset以获取最新的历史日志
        offsetRef.current = 0;
        getLog({ app_id: appId, since: offsetRef.current });
        pollingIntervalRef.current = window.setInterval(() => {
            getLog({ app_id: appId, since: offsetRef.current });
        }, 2000) as any;
        setIsPolling(true);
    };

    const stopPolling = () => {
        if (pollingIntervalRef.current) {
            clearInterval(pollingIntervalRef.current);
            pollingIntervalRef.current = null;
        }
        if (isPolling) {
            setIsPolling(false);
            message.info("已停止拉取日志");
        }
    };

    // 组件卸载时停止轮询
    useEffect(() => {
        return () => {
            stopPolling();
            if (scrollTimeoutRef.current) clearTimeout(scrollTimeoutRef.current);
        };
    }, []);

    // 自动滚动逻辑
    useEffect(() => {
        if (isAutoScrolling) scrollToBottom();
    }, [code]);

    // 编辑器滚动事件检测
    const handleEditorScroll = () => {
        if (scrollTimeoutRef.current) clearTimeout(scrollTimeoutRef.current);
        scrollTimeoutRef.current = setTimeout(() => {
            if (!editorRef.current) return;
            const editor = editorRef.current;
            const scrollTop = editor.getScrollTop();
            const scrollHeight = editor.getScrollHeight();
            const editorHeight = editor.getLayoutInfo().height;
            setIsAutoScrolling(scrollTop + editorHeight >= scrollHeight - 10);
        }, 100);
    };

    // 控制字体大小滚轮事件
    const handleFontSizeWheel = (e: React.WheelEvent) => {
        const delta = e.deltaY > 0 ? -1 : 1;
        setFontSize(Math.max(1, Math.min(50, fontSize + delta)));
    };

    // 控制按钮
    const handleConnectDisconnect = () => {
        if (isPolling) {
            stopPolling();
        } else {
            startPolling();
            setCode("// 连接成功，日志开始输出...\n");
        }
    };

    const handleScrollToBottom = () => {
        setIsAutoScrolling(true);
        scrollToBottom();
    };

    const handleClear = () => setCode("");

    const handleFind = () => {
        if (editorRef.current) {
            editorRef.current.focus();
            editorRef.current.trigger("", "actions.find", {});
        }
    };

    return (
        <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
            <div style={{ padding: "10px 16px", display: "flex", gap: 8, flexWrap: "wrap", background: "#fff", justifyContent: "space-between" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <span>字体大小：</span>
                    <InputNumber min={1} max={50} value={fontSize} onWheel={handleFontSizeWheel} onChange={val => setFontSize(val || 1)} />
                </div>
                <div style={{ display: "flex", gap: 8 }}>
                    <Button onClick={handleScrollToBottom} disabled={isPolling ? false : true}>回到底部并保持</Button>
                    <Button onClick={handleFind}>查找</Button>
                    <Button onClick={handleClear}>清空</Button>
                    <Button onClick={handleConnectDisconnect} type="primary" danger={isPolling}>
                        {isPolling ? "断开" : "连接"}
                    </Button>
                </div>
            </div>
            <div style={{ flex: 1, overflow: "hidden" }}>
                <Editor
                    height="100%"
                    language="log"
                    value={code}
                    onMount={(editor) => {
                        editorRef.current = editor;
                        editor.onDidScrollChange(handleEditorScroll);
                        scrollToBottom();
                    }}
                    options={{
                        readOnly: true,
                        fontSize,
                        wordWrap: "on",
                        smoothScrolling: true,
                        minimap: { enabled: true },
                        automaticLayout: true,
                        scrollBeyondLastLine: false,
                        cursorSmoothCaretAnimation: "on",
                        renderWhitespace: "selection",
                        tabSize: 4
                    }}
                />
            </div>
        </div>
    );
};

export default Realog;